package com.ly.mp.busicen.rule.field.msg;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ly.mp.busicen.common.constant.UserBusiEntity;
import com.ly.mp.busicen.rule.field.msg.ext.FieldMsg;
import com.ly.mp.busicen.rule.flow.FlowUserMode;

/**
 * 
 * @Description: com.ly.mp.busicen.rule.field.FiledRuleLoader.msgLoad() 初始化 加载了t_prc_db_log_model(错误信息构建表)
 */
public class FieldMsgContainer implements IFieldMsgContainer {
	
	Logger log = LoggerFactory.getLogger(FieldMsgContainer.class);
	
	private Map<String, Map<String, IFieldMsg>> errorMsgs = new HashMap<String, Map<String,IFieldMsg>>();
	
	private List<FieldMsg> fieldMsgs = new ArrayList<FieldMsg>();

	public List<FieldMsg> getFieldMsgs() {
		return fieldMsgs;
	}

	public void setFieldMsgs(List<FieldMsg> fieldMsgs) {
		this.fieldMsgs = fieldMsgs;
	}

	public Map<String, Map<String, IFieldMsg>> getErrorMsgs() {
		return errorMsgs;
	}

	public void setErrorMsgs(Map<String, Map<String, IFieldMsg>> errorMsgs) {
		this.errorMsgs = errorMsgs;
	}
	
	public Map<String, IFieldMsg> getErrors(String name) {
		Map<String, IFieldMsg> errors = errorMsgs.get(name);
		if (errors==null) {
			String err = String.format("规则【%s】的错误信息找不到", name);
			log.error(err);
			throw new RuntimeException(err);
		}
		return errors;
	}

	@Override
	public IFieldMsg getMsg(String name, String label) {
		UserBusiEntity userBusiEntity = FlowUserMode.currentUser();
		Optional<FieldMsg> opt = fieldMsgs.stream().filter(m->
				label.equals(m.getLabel())&&
				userBusiEntity.getBrandCode().equals(m.getBrandCode())&&
				userBusiEntity.getOemCode().equals(m.getOemCode())
				).findAny();
		if (opt.isPresent()) {
			return opt.get();
		}
		String error = String.format("【%s】错误信息找不到", label);
		log.error(error);
		throw new RuntimeException(error);
	}
	
	
	
//	@Override
//	public IFieldMsg getMsg(String name,String label) {
//		Map<String, IFieldMsg> errors = getErrors(name);
//		IFieldMsg errorMsg = errors.get(label);
//		if (errorMsg==null) {
//			String err = String.format("规则【%s】的【%s】错误信息找不到", name,label);
//			log.error(err);
//			throw new RuntimeException(err);
//		}
//		return errorMsg;
//	}
//	

}
